<!--created by yuyupeng-->
<!--2023/02/27-->
<!-- 部门管理-->
<template>
  <div class="list-card-container">
    <splitpanes class="default-theme">
      <pane min-size="10" size="18">
        <a-card title="组织机构树" class="general-card">
          <a-scrollbar style="height: calc(100vh - 150px); overflow: auto">
            <a-skeleton v-if="treeData.length === 0" animation>
              <!-- 还在加载的时候用骨架屏先占个位子，好看点 -->
              <a-skeleton-line :rows="10" />
            </a-skeleton>
            <div v-else>
              <a-input-search
                v-model="searchTreeKey"
                style="margin-bottom: 5px"
                @input="searchTreeData"
              />
              <a-tree
                v-model:selected-keys="selectedTreeKeys"
                v-model:expanded-keys="expandedTreeKeys"
                block-node
                :field-names="{
                  key: 'code',
                  title: 'name',
                  children: 'children',
                }"
                :data="treeDataFilter"
                @select="onSelectTreeNode"
                @expand="onExpandTreeNode"
              >
                <template #icon>
                  <icon-home />
                </template>
                <template #title="nodeData">
                  <span v-if="nodeData?.name.indexOf(searchTreeKey) > -1">
                    {{
                      nodeData?.name.substr(
                        0,
                        nodeData?.name.indexOf(searchTreeKey)
                      )
                    }}
                    <span style="color: #f50">{{ searchTreeKey }}</span>
                    {{
                      nodeData?.name.substr(
                        nodeData?.name.indexOf(searchTreeKey) +
                          searchTreeKey.length
                      )
                    }}
                  </span>
                  <span v-else>{{ nodeData?.name }}</span>
                </template>
              </a-tree>
            </div>
          </a-scrollbar>
        </a-card>
      </pane>
      <pane min-size="50" size="82">
        <a-card title="部门管理" class="general-card">
          <!-- 查询表单 -->
          <AdvancedSearch
            ref="searchRef"
            :data-source="searchItemList"
            @change="searchByParams"
          />
          <a-space style="margin-top: 5px; margin-bottom: 5px">
            <AdvancedDrawer
              click="button"
              title="新增部门信息"
              clickword="新增部门"
              :rules="advancedDrawerRules"
              :data-source="addDrawerConfig"
              @change="addDrawerSubmit"
            />
            <a-popconfirm
              content="确定删除吗?"
              type="warning"
              @ok="deleteTbDataList(selectedKeys)"
            >
              <a-button :disabled="selectedKeys.length === 0"
                ><icon-delete />批量删除</a-button
              >
            </a-popconfirm>
            <a-button @click="exportToExcel"
              ><icon-download />导出Excel</a-button
            >
            <a-button @click="openImportExcelModal"
              ><icon-upload />导入Excel</a-button
            >
          </a-space>
          <!-- 表格 -->
          <a-table
            v-model:selectedKeys="selectedKeys"
            row-key="id"
            column-resizable
            :columns="tbCols"
            :data="tbData"
            :row-selection="rowSelection"
            :pagination="pagination"
            :loading="tbLoading"
            :scroll="{ x: '100%', y: 400 }"
            :scrollbar="true"
            @page-change="onPageChange"
            @page-size-change="onPageSizeChange"
          >
            <!-- 插槽-一键复制 -->
            <template #quickCopyToolTip="{ record, column }">
              <quick-copy-tool-tip
                :show-text="record[column['dataIndex']]"
                show-btn
              />
            </template>
            <!-- 插槽-状态 -->
            <template #status="{ record }">
              <a-tag v-if="record.status === 1" color="#86909c">停用</a-tag>
              <a-tag v-else-if="record.status === 0" color="#00b42a"
                >正常</a-tag
              >
            </template>
            <!-- 插槽-操作 -->
            <template #operation="{ record }">
              <a-space>
                <AdvancedDrawer
                  click="link"
                  title="修改部门信息"
                  clickword="修改"
                  :rules="advancedDrawerRules"
                  :data-source="editDrawerConfig"
                  :data-record="record"
                  @open="initEditDrawer(record)"
                  @change="editDrawerSubmit"
                />
                <a-popconfirm
                  content="确定删除吗?"
                  type="warning"
                  @ok="deleteTbData(record.id)"
                >
                  <a-link type="text" :disabled="record.children">删除</a-link>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>
      </pane>
    </splitpanes>
    <!-- 导入Excel弹窗 -->
    <AdvancedFormModal
      ref="importExcelModalRef"
      width="600px"
      title="导入部门数据"
      :items="importExcelModalConfig"
      @ok="importExcelModalSubmit"
    >
      <template #otherSlot>
        <a-row style="width: 100%" :gutter="[16, 16]">
          <a-col :span="24">
            <a-alert
              >提示：请按模板样式导入Excel
              <a-button type="text" @click="downloadDeptImportTemplate">
                <template #icon> <icon-download /> </template>
                下载模板</a-button
              ></a-alert
            >
          </a-col>
          <a-col :span="24">
            <a-upload
              accept=".xlsx, .xls, .csv"
              :file-list="fileList"
              :limit="1"
              :auto-upload="false"
              :show-cancel-button="false"
              @change="uploadChange"
            >
              <a-button> 选择文件 </a-button>
            </a-upload>
          </a-col>
        </a-row>
      </template>
    </AdvancedFormModal>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { FileItem, Notification } from '@arco-design/web-vue';
  import { DeptRecord } from '@/api/system/model/deptModel';
  import dayjs from 'dayjs';
  import {
    // queryDeptRecordList,
    addDeptRecord,
    editDeptRecord,
    deleteDeptRecords,
    exportDataToExcel,
    queryDeptRecordTreeList,
    importExcelToData,
  } from '@/api/system/dept';
  import { ref, onMounted, reactive, watch } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import AdvancedFormModal from '@/common/components/cac-components/advanced-form-modal/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';
  import { Splitpanes, Pane } from 'splitpanes';
  import 'splitpanes/dist/splitpanes.css';

  /**
   * data
   */
  const treeData = ref<any[]>([]); // 树
  const treeDataFilter = ref<any[]>([]); // 用于搜索的过滤树
  const filterKeySet = new Set(); // 定义一个集合，用于记录过滤keys
  const searchTreeKey = ref<string>(); // 树顶上的搜索框关键字
  const dataList = ref<any[]>([]); // treeData的所有key:title
  const parentKeys = ref<string[]>([]); // 用于存储点击的树节点的所有父节点的key
  // 表格
  const tbData = ref<DeptRecord[]>([]);
  const tbCols = [
    /* {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    }, */
    /* {
      title: '部门ID',
      dataIndex: 'id',
      fixed: 'left',
      width: 150,
      ellipsis: true,
      tooltip: true,
      align: 'center',
    }, */
    {
      title: '部门名称',
      dataIndex: 'name',
      width: 100,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '部门编码',
      dataIndex: 'code',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '部门状态',
      dataIndex: 'status',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'status',
    },
    /* {
      title: '父部门id',
      dataIndex: 'parentId',
      width: 180,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '父级部门索引',
      dataIndex: 'pids',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '显示顺序',
      dataIndex: 'sort',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '负责人',
      dataIndex: 'leaderUserId',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '所属部门ID',
      dataIndex: 'deptId',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    },
    {
      title: '所属组织机构ID',
      dataIndex: 'orgId',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    }, */
    /* { title: '创建者', dataIndex: 'creator', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '创建时间', dataIndex: 'createTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '更新ip', dataIndex: 'updateIp', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '是否删除', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '数据密级', dataIndex: 'secretLevel', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' },
    { title: '乐观锁', dataIndex: 'version', width: 150, ellipsis: true, align: 'center', tooltip: true, slotName: 'quickCopyToolTip' }, */
    /* {
      title: '租户编号',
      dataIndex: 'tenantId',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
      slotName: 'quickCopyToolTip',
    }, */
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 120,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const importExcelModalRef = ref<any>();
  const tbLoading = ref<boolean>(false);
  const treeDataLoading = ref<boolean>(false); // 指示树形组件是否正在加载中
  const expandedTreeKeys = ref<string[]>([]); // 已展开的树节点keys
  const selectedTreeKeys = ref<string[]>([]); // 已选中的树节点keys
  // 勾选框
  const selectedKeys = ref([]);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: false,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    // { type: 'text', labelText: '部门id', fieldName: 'id'},
    { type: 'text', labelText: '部门名称', fieldName: 'name' },
    { type: 'text', labelText: '部门编码', fieldName: 'code' },
    // { type: 'text', labelText: '父部门id', fieldName: 'parentId'},
    // { type: 'text', labelText: '父级部门索引', fieldName: 'pids'},
    // { type: 'text', labelText: '显示顺序', fieldName: 'sort'},
    // { type: 'text', labelText: '负责人', fieldName: 'leaderUserId'},
    {
      type: 'select',
      labelText: '部门状态',
      fieldName: 'status',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
    },
    { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'},
    { type: 'text', labelText: '租户编号', fieldName: 'tenantId'}, */
  ];
  // 新增抽屉配置项
  const addDrawerConfig = [
    // { type: 'text', labelText: '部门id', fieldName: 'id'},
    { type: 'text', labelText: '部门名称', fieldName: 'name' },
    { type: 'text', labelText: '部门编码', fieldName: 'code' },
    {
      type: 'select-tree',
      labelText: '父部门',
      fieldName: 'parentDept',
      codefield: 'id',
      namefield: 'name',
      data: treeData,
      allowClear: true,
    },
    /* { type: 'text', labelText: '父部门id', fieldName: 'parentId' },
    { type: 'text', labelText: '父级部门索引', fieldName: 'pids' }, */
    {
      type: 'number',
      labelText: '显示顺序',
      fieldName: 'sort',
      initialValue: 0,
    },
    { type: 'text', labelText: '负责人', fieldName: 'leaderUserId' },
    {
      type: 'select',
      labelText: '部门状态',
      fieldName: 'status',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
      initialValue: 0,
    },
    { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  // 修改抽屉配置项
  const editDrawerConfig = [
    { type: 'text', labelText: '部门id', fieldName: 'id', disabled: true },
    { type: 'text', labelText: '部门名称', fieldName: 'name' },
    { type: 'text', labelText: '部门编码', fieldName: 'code' },
    {
      type: 'select-tree',
      labelText: '父部门',
      fieldName: 'parentDept',
      codefield: 'id',
      namefield: 'name',
      data: treeData,
      allowClear: true,
    },
    /* { type: 'text', labelText: '父部门id', fieldName: 'parentId' },
    { type: 'text', labelText: '父级部门索引', fieldName: 'pids' }, */
    {
      type: 'number',
      labelText: '显示顺序',
      fieldName: 'sort',
      initialValue: 0,
    },
    { type: 'text', labelText: '负责人', fieldName: 'leaderUserId' },
    {
      type: 'select',
      labelText: '部门状态',
      fieldName: 'status',
      codefield: 'value',
      namefield: 'label',
      options: [
        { label: '停用', value: 1 },
        { label: '正常', value: 0 },
      ],
      initialValue: 0,
    },
    { type: 'text', labelText: '所属部门ID(非必须)', fieldName: 'deptId' },
    { type: 'text', labelText: '所属组织机构ID(非必须)', fieldName: 'orgId' },
    /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除(非必须)', fieldName: 'deleted'},
    { type: 'text', labelText: '数据密级(非必须)(0:公开,5内部,6秘密,7机密,8绝密)', fieldName: 'secretLevel'},
    { type: 'text', labelText: '乐观锁', fieldName: 'version'}, */
    /* { type: 'text', labelText: '租户编号', fieldName: 'tenantId' }, */
  ];
  // 抽屉表单项校验配置
  const advancedDrawerRules = ref({
    code: [{ required: true, message: '请输入部门编码' }],
    name: [{ required: true, message: '请输入部门名称' }],
    // parentDept: [{ required: true, message: '请选择父部门' }],
    sort: [{ required: true, message: '请输入显示顺序' }],
  });
  // 导入Excel弹窗配置项
  const importExcelModalConfig = [
    {
      span: 24,
      type: 'other',
      labelText: '',
      fieldName: 'otherSlot',
    },
  ];
  const fileList = ref<FileItem[]>([]); // 文件上传组件绑定的fileList
  /**
   * watch
   */
  watch(
    () => parentKeys,
    (val) => {
      if (val) {
        val.value.forEach((element: any) => {
          filterKeySet.add(element);
        });
        // 进行过滤操作
        treeDataFilter.value = treeData.value.filter((item) =>
          filterKeySet.has(item.code)
        );
        expandedTreeKeys.value = [...filterKeySet] as string[];
      }
    },
    { deep: true, immediate: true }
  );
  /**
   * func
   */
  /**
   * @description 获取部门的树形结构信息
   */
  const getTreeData = async () => {
    treeDataLoading.value = true;
    treeData.value = [];
    treeDataFilter.value = [];
    try {
      const { data } = await queryDeptRecordTreeList({});
      treeData.value = data;
      treeDataFilter.value = data;
      dataList.value = [];
      generateList(treeData.value);
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      treeDataLoading.value = false;
    }
  };
  /**
   * @description 构建treeData的所有 { key: title } 数组
   * @param data 树节点数据
   */
  const generateList = (data: any) => {
    // 创建dataList 递归调用
    data.forEach((item: any) => {
      const node = item;
      const key = node.code;
      dataList.value.push({ key, title: node.name });
      if (node.children) {
        generateList(node.children);
      }
    });
  };
  /**
   * @description 根据子节点的key获取父节点的key
   * @param key key
   * @param tree 树节点
   */
  const getParentKey = (key: string, tree: any) => {
    let parentKey;
    tree.forEach((elem: any) => {
      const node = elem;
      if (node.children) {
        if (node.children.some((item: any) => item.code === key)) {
          parentKey = node.code;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    });
    return parentKey;
  };
  /**
   * @description 获取完整地父节点的key数组 递归调用
   * @param key
   */
  const getWholeParentKeys = (key: string) => {
    const temp = getParentKey(key, treeData.value);
    if (temp !== undefined) {
      parentKeys.value.push(temp);
      getWholeParentKeys(temp);
    }
  };
  /**
   * @description 树形结构上面的搜索框发生改变会触发此函数
   * @param value
   */
  const searchTreeData = (val: any) => {
    const value = val.replaceAll(' ', '');
    filterKeySet.clear();
    // 进行搜索操作
    const expandedKeysTemp = [] as any[];
    dataList.value.forEach((item) => {
      if (item.title && item.title.indexOf(value) > -1) {
        expandedKeysTemp.push(item.key);
      }
    });
    parentKeys.value = [];
    // 必须要有下面这个forEach，否则只能查到2层数据，因为超过了2层后匹配不到更上层的父id，进而导致搜索不出结果
    expandedKeysTemp.forEach((item: string) => {
      filterKeySet.add(item);
      getWholeParentKeys(item); // 把原始的expandedKeysTemp中的每个key对应的完整父key都放进parentKeys保存
    });
    expandedTreeKeys.value =
      value.trim().length === 0 ? [] : ([...filterKeySet] as string[]);
    searchTreeKey.value = value;
    // 进行过滤操作
    treeDataFilter.value = treeData.value.filter((item) =>
      filterKeySet.has(item.code)
    );
  };
  /**
   * @method
   * @description 获取表格数据，这里比较特殊，数据有children属性，属于树形结构，所以没有用分页接口
   */
  const getTbDataByPage = async (reqdata: any = {}) => {
    /* const params: DeptParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...reqdata,
    }; */
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const { data } = await queryDeptRecordTreeList(reqdata);
      tbData.value = data;
      pagination.total = Number(data.length); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    getTbDataByPage(reqdata);
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    console.log(pageSize);
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 新增抽屉提交
   */
  const addDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    reqdata.parentId = reqdata.parentDept || 0; // TODO 还剩个父级部门索引pids没有设置，暂时不知道如何设置，前端遍历有点麻烦，或许可以让后端做
    delete reqdata.parentDept;
    console.log(reqdata);
    try {
      const res = (await addDeptRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '保存成功！',
        });
      } else {
        Notification.error({
          title: '保存失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
      getTreeData(); // 左侧的树也更新一下
    }
  };
  /**
   * @description 打开编辑抽屉的时候对数据进行一些初始化的操作
   * @param record
   */
  const initEditDrawer = (record: any) => {
    record.parentDept = record.parentId; // 此举意在抽屉里用到了select-tree组件，能够确保正确设置初始值
  };
  /**
   * @method
   * @description 修改抽屉提交
   */
  const editDrawerSubmit = async (reqdata: any) => {
    console.log(reqdata);
    reqdata.parentId = reqdata.parentDept || 0; // TODO 还剩个父级部门索引pids没有设置，暂时不知道如何设置，前端遍历有点麻烦，或许可以让后端做
    delete reqdata.parentDept;
    console.log(reqdata);
    try {
      const res = (await editDeptRecord(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '修改成功！',
        });
      } else {
        Notification.error({
          title: '修改失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
      getTreeData(); // 左侧的树也更新一下
    }
  };
  /**
   * @method
   * @description 删除部门信息
   */
  const deleteTbData = async (id: string) => {
    const reqdata = [];
    reqdata.push(id);
    try {
      const res = (await deleteDeptRecords(reqdata)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
      getTreeData(); // 左侧的树也更新一下
    }
  };
  /**
   * @method
   * @description 批量删除部门信息，传id数组，支持批量
   */
  const deleteTbDataList = async (ids: string[]) => {
    try {
      const res = (await deleteDeptRecords(ids)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
      getTreeData(); // 左侧的树也更新一下
    }
  };
  /**
   * @method
   * @description 导出到Excel
   */
  const exportToExcel = async () => {
    try {
      const res = (await exportDataToExcel()) as any;
      console.log(res);
      if (res.code === null || res.code === undefined) {
        const elink = document.createElement('a');
        elink.download = `部门信息导出数据${dayjs()
          .format('YYYY-MM-DD_HH:mm:ss')
          .toString()}.xlsx`;
        elink.style.display = 'none';
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        console.log(blob);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      } else {
        // 正常情况下文件的下载是不会返回retCode的，如果发现有返回码，说明就是接口出了问题
        Notification.error({
          title: '导出失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * 打开导入Excel对话框
   */
  const openImportExcelModal = () => {
    fileList.value = [];
    importExcelModalRef.value.open();
  };
  /**
   * 点击树节点触发
   * @param newSelectedKeys
   * @param event
   */
  const onSelectTreeNode = (newSelectedKeys: any, event: any) => {
    // console.log('select: ', newSelectedKeys, event);
    selectedTreeKeys.value = newSelectedKeys;
    if (event.node.children) {
      let flag = false;
      expandedTreeKeys.value.forEach((item: string) => {
        if (item === newSelectedKeys[0]) {
          flag = true;
        }
      });
      if (!flag) {
        expandedTreeKeys.value.push(newSelectedKeys[0]);
      }
    }
    /* const searchParams = { parentId: event.node.id };
    getTbDataByPage(searchParams); */
  };
  /**
   * 展开树节点触发
   * @param newExpandedKeys
   * @param event
   */
  const onExpandTreeNode = (newExpandedKeys: any, event: any) => {
    console.log('expand: ', newExpandedKeys, event);
  };
  /**
   * @method
   * @description 导入Excel弹窗提交
   */
  const importExcelModalSubmit = async () => {
    if (fileList.value.length > 0) {
      const formData = new FormData();
      console.log(fileList.value[0].file);
      formData.append('file', fileList.value[0].file as any);
      try {
        const res = (await importExcelToData(formData)) as any;
        if (res.code === 200) {
          Notification.success({
            content: '导入成功！',
          });
        } else {
          Notification.error({
            title: '导入失败！',
            content: res.message,
          });
        }
      } catch (error) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        Notification.error({
          content: `出现异常！${error}`,
          closable: true,
        });
      } finally {
        searchRef.value.handleSubmit(); // 与搜索结果保持一致
      }
    } else {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.warning({
        content: '请选择文件！',
        closable: true,
      });
    }
  };
  /**
   * @method
   * @description uploade组件自定义的上传请求参数
   */
  /* const customRequest = (option: any) => {
    const { onProgress, onError, onSuccess, fileItem } = option;
    const xhr = new XMLHttpRequest();
    if (xhr.upload) {
      xhr.upload.onprogress = (event: any) => {
        let percent;
        if (event.total > 0) {
          // 0 ~ 1
          percent = event.loaded / event.total;
        }
        onProgress(percent, event);
      };
    }
    xhr.onerror = function error(e) {
      onError(e);
    };
    xhr.onload = function onload() {
      if (xhr.status < 200 || xhr.status >= 300) {
        return onError(xhr.responseText);
      }
      return onSuccess(xhr.response);
    };

    const formData = new FormData();
    formData.append('file', fileItem.file);
    xhr.open('post', url.value, true);
    xhr.send(formData);

    return {
      abort() {
        xhr.abort();
      },
    };
  }; */
  /**
   * @description 文件上传组件改动触发
   * @param fileList
   * @param file
   */
  const uploadChange = (files: FileItem[], file: FileItem) => {
    file.status = 'uploading';
    fileList.value = [...files];
  };
  /**
   * @description 下载模板，写死的url，这个模板是通过【文件管理】页面托管的，如果下载模板出了问题，可能是文件服务有问题
   */
  const downloadDeptImportTemplate = () => {
    window.open(
      'http://10.1.247.122:9000/system/导入部门信息（模板）.xlsx',
      '_blank'
    );
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTreeData();
    getTbDataByPage();
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
